<!--
 @description  客户Item
 @fileName index.vue
 @author zengqiongying
 @created 2022/10/25 11:20:55
-->
<template>
  <div class="customer-item" @click="handleDetail">
    <div class="item-head">
      <span class="i-time">{{ itemData.filingTime | filterTime }}</span>
      <template>
        <!-- 客户等级ABCD -->
        <img v-if="itemData.consumerLevel==='A'" src="@/assets/img/level-1.png" class="i-level">
        <img v-if="itemData.consumerLevel==='B'" src="@/assets/img/level-2.png" class="i-level">
        <img v-if="itemData.consumerLevel==='C'" src="@/assets/img/level-3.png" class="i-level">
        <img v-if="itemData.consumerLevel==='D'" src="@/assets/img/level-4.png" class="i-level">
      </template>
    </div>
    <div class="people-box">
      <div class="p-name">
        <div class="name">{{ itemData.name || '--' }}</div>
        <template v-if="itemData.gender==='Male' || itemData.gender==='Female'">
          <img v-if="itemData.gender==='Male'" class="icon-sex" src="@/assets/img/sex-man.png">
          <img v-if="itemData.gender==='Female'" class="icon-sex" src="@/assets/img/sex-woman.png">
        </template>
        <div class="row-right">
          <!-- 意向客户跟进 -->
          <span v-if="customerType===2 && noFollowDateCount>0 && (itemData.clueCustomerType!=='OrderedCustomer'&&itemData.clueCustomerType!=='FailureCustomer')" class="f-tip">{{ noFollowDateCount }}天未跟进</span>
        </div>
      </div>
      <div v-if="itemData.labels && itemData.labels.length>0" class="p-tips">
        <span v-for="(l,i) in getLabelList(itemData)" :key="i">{{ l.labelName }}</span>
      </div>
      <div class="p-tel">
        <span>电话：{{ itemData.phone || '--' }}</span>
        <!-- 跟进人默认显示两个，多余的... -->
        <span>跟进人：{{ getFollowUser(itemData.clueFollowUpUsers) }}</span>
      </div>
      <div v-if="!!(itemData.lastFollowupId)" class="p-distr">
        <!-- 最新跟进记录 -->
        <img class="icon" src="@/assets/img/icon-opty.png">
        <div class="con">
          <div class="time">{{ itemData.lastFollowupTime | filterLastTime }}</div>
          <div class="ellipsis">{{ itemData.lastFollowupContent || '--' }}</div>
        </div>
        <div class="s-name">
          <!--取跟进记录的来源类型 -->
          {{ getFollowupType(itemData.lastFollowupType) }}
        </div>
      </div>
      <div class="p-bottom">
        <div v-if="isShowOptyBtn" class="btn btn-main" @click.stop="handleTooptyPage">商机处理</div>
        <!--
          公告客户池(待分配)：分配,(添加标签，退回总部，客户流失)
          公告客户池(已分配):分配，(添加标签，客户流失)
          公告客户池(无效):分配
          意向客户：收款，跟进，(添加标签，退回门店，创建商机)
          潜在客户：转意向客户，跟进，(添加标签，退回门店)
        -->
        <div
          v-for="(l,i) in outerBtns"
          :key="i"
          class="btn btn-main"
          @click.stop="handleToPage(l.url)"
        >{{ l.buttonName }}</div>

        <MoreBtn
          v-if="!(customerType===0 && (commonStatus===3 || commonStatus===0)) && moreBtns.length>0"
          class="btn"
          :opt-menu="moreBtns"
          @change="handleMenuChange"
          @click.native.stop=""
        />
      </div>
    </div>

    <Popup
      v-if="popConfig.show"
      v-model="popConfig.show"
      :message="popConfig.message"
      :confirm-button-text="popConfig.confirmText"
      msg-align="center"
      :icon="popConfig.icon"
      @confirm="handlePopConfirm"
    />
  </div>
</template>

<script>
import Popup from '@/components/Popup'
import MoreBtn from './MoreBtn'
import { parseTime } from '@/utils'
export default {
  name: 'CustomerItem',
  components: { Popup, MoreBtn },
  filters: {
    filterTime(val) {
      return parseTime(val, '{y}-{m}-{d} {h}:{i}')
    },
    filterLastTime(val) {
      return parseTime(val, '{y}.{m}.{d} {h}:{i}')
    }
  },
  props: {
    customerType: {
      type: Number,
      default: 0 // 客户类型：0 公共客户池 ，潜客：1 ，意向客户：2
    },
    commonStatus: {
      type: Number,
      default: 0 // 公告客户池客户状态：0 全部 ，待分配 1 ，已分配 2 ， 3 流失客户
    },
    itemData: {
      type: Object,
      default: () => {}
    },
    followUpTypes: {
      // 跟进记录类型数据字典
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      buttonList: [
        // outerType:指定外部按钮显示对应客户类型，
        // moreType : 指定更多按钮操作显示对应客户类型,
        // customerState :指定客户状态(仅公告客户池使用)
        // url: 页面地址
        { buttonName: '分配', optCode: 'allocation', outerType: [0], url: '/customer/allocation' },
        { buttonName: '收款', optCode: 'receipt', outerType: [2], url: '/customer/receipt' },
        { buttonName: '转意向客户', optCode: 'turnIntention', outerType: [1], url: '/customer/turnIntention' },
        { buttonName: '跟进', optCode: 'followUp', outerType: [1, 2], url: '/customer/followUp/customer' },

        { buttonName: '添加标签', optCode: 'addTag', moreType: [0, 1, 2], url: '/customer/addTag' },
        { buttonName: '退回总部', optCode: 'sendBack', moreType: [0], customerState: [1], url: '/customer/sendBack' },
        { buttonName: '客户流失', optCode: 'losing', moreType: [0], url: '/customer/losing' },
        { buttonName: '退回门店', optCode: 'sendBackShop', moreType: [1, 2], url: '/customer/sendBackShop' },
        { buttonName: '创建商机', optCode: 'opty', moreType: [2], url: '/customer/opty/create' }
      ],
      popConfig: {
        show: false,
        message: '',
        confirmText: '',
        confirmFn: null,
        icon: ''
      }
    }
  },

  computed: {
    positionCodes() {
      const t = this.$store.getters.userInfo
      return t.positionCodes || []
    },
    // 外部按钮
    outerBtns() {
      const btns = this.buttonList.filter(v => {
        return v.outerType && v.outerType.includes(this.customerType)
      })
      if (this.customerType === 0) {
        // 公共客户池
        // 只有设计主管 top_design_mg 岗位时，公共客户池 列表及对应的客户详情页，不展示 ‘分配’按钮、不展示‘更多-客户流失’ 按钮
        // 店长 top_shop_mg 、线上对接人 top_online_mg 、经理 top_dis  才有
        if (this.positionCodes.length === 1 && this.positionCodes[0] === 'top_design_mg') {
          return btns.filter(v => v.optCode !== 'allocation')
        }
      }
      return btns
    },
    // 更多按钮
    moreBtns() {
      const list = this.buttonList.filter(v => {
        let flag = v.moreType && v.moreType instanceof Array ? v.moreType.includes(this.customerType) : false
        if (!flag) return false
        if (v.customerState || v.customerState instanceof Array) {
          flag = v.customerState.includes(this.commonStatus)
        }
        if (flag && v.optCode === 'sendBack') {
          // 退回总部条件：仅终端一级来源为线上，且是否自投为否的客户
          const { disCustomerFirstSource, isDisAdvertisement } = this.itemData
          return disCustomerFirstSource === 'Online' && ['0', 0].includes(isDisAdvertisement)
        }
        return flag
      })
      if (this.customerType === 0) {
        // 公共客户池
        // 只有设计主管 top_design_mg 岗位时，公共客户池 列表及对应的客户详情页，不展示 ‘分配’按钮、不展示‘更多-客户流失’ 按钮
        // 店长 top_shop_mg 、线上对接人 top_online_mg 、经理 top_dis  才有
        if (this.positionCodes.length === 1 && this.positionCodes[0] === 'top_design_mg') {
          return list.filter(v => v.optCode !== 'losing')
        }
      }
      return list
    },
    // 未跟进时间
    noFollowDateCount() {
      if (this.customerType !== 2) return 0
      const lastFollowupTime = this.itemData.lastFollowupTime || ''
      let count = 0
      if (lastFollowupTime) {
        const now = new Date().getTime()
        const start = new Date(lastFollowupTime).getTime()
        const d = now - start
        count = parseInt(d / 1000 / 60 / 60 / 24)
      }

      return count
    },
    // 是否显示商机处理(当前职务为：设计师 top_designer 和设计主管 top_design_mg ，店长 top_shop_mg 时显示),潜在客户/流失客户不显示
    isShowOptyBtn() {
      // if (this.customerType !== 2) return false
      if (['PotentialCustomer', 'FailureCustomer'].includes(this.itemData.clueCustomerType)) return false
      const t = this.$store.getters.userInfo
      if (t.positionCodes && t.positionCodes.length > 0) {
        const codes = ['top_designer', 'top_design_mg', 'top_shop_mg']
        return t.positionCodes.some(v => codes.includes(v))
      }
      return false
    }
  },
  watch: {
    'popConfig.show'(v) {
      if (!v) {
        this.popConfig = {
          show: false,
          message: '',
          confirmText: '',
          icon: '',
          confirmFn: null
        }
      }
    }
  },

  created() {},

  mounted() {},

  methods: {
    getLabelList(d) {
      return d.labels || []
    },
    getFollowupType(code) {
      if (this.followUpTypes && this.followUpTypes.length > 0) {
        const dict = this.followUpTypes.find(v => v.dictCode === code)
        return dict && dict.dictCode || code
      }
      return code
    },
    getFollowUser(user) {
      if (!user || user.length === 0) return '--'
      const names = user.map(v => v.userTrueName)
      if (names.length > 2) {
        return `${names.slice(0, 2).join(',')}...`
      } else {
        return names.join(',')
      }
    },
    handleDetail() {
      this.$router.push({
        path: '/customer/detail',
        query: { id: this.itemData.id, type: this.customerType }
      })
    },
    handleToPage(path) {
      const { id, name, shopDeptCode, phone, disCode } = this.itemData
      const query = { id, name }
      if (path === '/customer/turnIntention' || path === '/customer/opty/create') {
        if (path === '/customer/turnIntention') {
          let flag = true
          const msg = []
          const addrs = 'provinceCode cityCode districtsCode detailedAddress'.split(' ')
          if (addrs.some(e => !this.itemData[e])) {
            msg.push('地址不完整')
            flag = false
          }
          if (!phone) {
            msg.push('联系电话为空')
          }
          if (!flag) {
            this.popConfig = {
              show: true,
              message: msg.join(',') + ',不允许转意向客户',
              confirmText: '前往修改',
              icon: 'warning',
              confirmFn: () => {
                this.$router.push({
                  path: '/customer/add',
                  query: {
                    id: this.itemData.id,
                    type: this.customerType === 2 ? 2 : 1
                  }
                })
              }
            }
            return
          }
        }
        if (!shopDeptCode) {
          this.$toast('门店组织异常，无法操作')
          return
        }
        query.shopDeptCode = shopDeptCode
        query.disCode = disCode
      } else if (path === '/customer/allocation') {
        query.disCode = disCode
      } else if (path === '/customer/addTag') {
        query.source = this.customerType === 0 ? 'commonpool' : 'mypool'
      }
      this.$router.push({
        path,
        query
      })
    },
    handleMenuChange(optCode) {
      const obj = this.buttonList.find(v => v.optCode === optCode)
      const path = obj && obj.url || ''
      if (path) {
        this.handleToPage(path)
      } else {
        this.$toast('操作异常!')
      }
    },
    handlePopConfirm() {
      const Fn = this.popConfig.confirmFn
      Fn && Fn()
      this.popConfig.show = false
    },
    handleTooptyPage() {
      this.$router.push({
        path: '/customer/detail',
        query: { id: this.itemData.id, type: this.customerType, anchor: 'opty' }
      })
    }
  }
}

</script>
<style lang='less' scoped>
.customer-item{
  padding: 0 16px 16px;
  background: #FFFFFF;
  border-radius: 16px;
  margin-bottom: 16px;
  .item-head{
    position: relative;
    height: 44px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    &::after{
      content: '';
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      height: 1px;
      background: #EFF2F7;
      // -webkit-transform: scaleY(0.5);
      // transform: scaleY(0.5);
    }
  }
  .i-time{
    font-size: 14px;
    color: #3C4458;
  }
  .i-level{
    width:40px;
    height: 38px;
  }
}
.people-box{
  margin-top:16px;
  .p-name{
    height: 25px;
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    align-items: center;
    .name{
      line-height: 25px;
      font-size: 18px;
      font-weight: bold;
      color: #3C4458;
    }
    .row-right{
      flex: 1;
      display: flex;
      margin-left: 10px;
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
    .f-tip{
      padding: 0 6px;
      height: 20px;
      line-height: 20px;
      color: #EE671A;
      font-size: 10px;
      background:rgba(238, 103, 26, .1);
      border-radius: 6px;
      box-sizing: border-box;
    }
  }
  .icon-sex{
    width: 16px;
    height: 16px;
    margin-left: 6px;
  }
  .p-tips{
    margin-bottom: 5px;
    display: flex;
    flex-wrap: wrap;
    color: #7D8091;
    font-size: 10px;
    line-height: 1;
    >span{
      display: inline-block;
      margin: 0 8px 5px 0;
      padding: 0 6px;
      height: 20px;
      line-height: 18px;
      border-radius: 10px;
      border: 1px solid rgba(52, 54, 64, .1);
      box-sizing: border-box;
    }
  }
  .p-tel{
    margin-bottom: 16px;
    height: 18px;
    line-height: 18px;
    color: #7D8091;
    font-size: 12px;
    >span:last-child{
      margin-left: 16px;
    }
  }
  .p-distr{
    padding: 10px 12px;
    background: rgba(223, 228, 239, .16);
    border-radius: 6px;
    display: flex;
    .icon{
      width: 42px;
      height: 42px;
      background: linear-gradient(360deg, #E8FFF7 0%, #88F2CD 100%);
      border-radius: 11px;
      margin-right: 8px;
    }
    .s-name{
      height: 42px;
      line-height: 42px;
      color: #3C4458;
      font-size: 12px;
      font-weight: bold;
      margin-left: 10px;
    }
    .con{
      flex: 1;
      line-height: 18px;
      height:42px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      color: #7C89A7;
      font-size: 12px;
      .ellipsis{
        width:100%;
        word-break: break-all;
        text-overflow: ellipsisis;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 1;
        overflow: hidden;
      }
    }
  }
  .p-bottom{
    margin-top:16px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    .btn{
      display: inline-block;
      margin-left:16px;
      padding: 0 16px;
      width: auto;
      height: 32px;
      line-height: 30px;
      border-radius: 8px;
      box-sizing: border-box;
      border:1px solid rgba(22, 188, 131, .12);
      background: #FFFFFF;
      color: #16BC83;
      font-size: 12px;
      font-weight: 600;
      text-align: center;
      white-space: nowrap;
      &.btn-main{
        background: rgba(22, 188, 131, .12);
      }
    }
  }
}
</style>
